from flask_wtf import FlaskForm, RecaptchaField
from wtforms import StringField, TextAreaField, PasswordField, BooleanField
from wtforms.validators import DataRequired, Length, EqualTo, URL

from BookWorldWeb.models import User


class CommentForm(FlaskForm):
    """
    评论表单
    """

    name = StringField(
        'Name',
        validators=[DataRequired(), Length(max=255)]
    )
    text = TextAreaField(u'Comment', validators=[DataRequired()])


class LoginForm(FlaskForm):
    """
    登录表单
    """

    username = StringField('Username', [DataRequired(), Length(255)])
    password = PasswordField('Password', [DataRequired()])

    def validate(self):
        check_validate = super(LoginForm, self).validate()

        # 如果验证没通过
        if not check_validate:
            return False

        # 检查是否存在拥有该用户名的用户
        user = User.query.filter_by(
            username=self.username.data
        ).first()
        if not user:
            self.username.errors.append(
                'Invalid username or password'
            )
            return False

        # 检查密码是否匹配
        if not user.check_password(self.password.data):
            self.username.errors.append(
                'Invalid username or password'
            )
            return False

        return True


class RegisterForm(FlaskForm):
    """
    注册表单
    """

    username = StringField('Username', [DataRequired(), Length(max=255)])
    password = PasswordField('Password', [DataRequired(), Length(min=8)])
    confirm = PasswordField('Confirm Password', [DataRequired(), EqualTo('password')])

    recaptcha = RecaptchaField()

    def validate(self):
        check_validate = super(RegisterForm, self).validate()

        # 如果验证没通过
        if not check_validate:
            return False

        user = User.query.filter_by(
            username=self.username.data
        ).first()

        # 如果该用户名已经被使用了
        if user:
            self.username.errors.append(
                'User with that name already exists'
            )
            return False

        return True


class PostForm(FlaskForm):
    """
    博客表单
    """

    title = StringField('Title', [DataRequired(), Length(max=255)])
    text = TextAreaField('Content', [DataRequired()])
